import React from 'react';
import Title from 'Page/CommonComponents/Title';
import { ListView } from 'antd-mobile';
import Api from 'Utils/api';
import DOCUMENT_TYPE from 'Constants/documentType';
import dialog from 'Utils/dialog';
import moment from 'moment/moment';
import { RESOURCE_HOST } from 'Constants/config';
import { connect } from 'react-redux';
import * as routerAction from 'react-router-redux';
import './index.scss';

class NormalWork extends React.PureComponent {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });
    this.state = {
      dataSource: dataSource.cloneWithRows([]),
      data: [],
      // 分页信息
      pageSize: 20,
      totalCount: 0,
      offset: 0,
      isLoading: true,
      hasMore: true
    };
    this.initList = ::this.initList;
    this.onEndReached = ::this.onEndReached;
  }
  componentWillMount() {
    this.initList();
  }
  // 上拉加载触发函数
  onEndReached() {
    this.setState({ isLoading: true }, () => {
      this.initList();
    });
  }
  initList() {
    const { pageSize, dataSource, offset } = this.state;
    const self = this;
    const api = new Api({
      method: 'GET',
      path: `/documents/user/list/${DOCUMENT_TYPE.WORK}`,
      query: {
        limit: pageSize,
        offset
      },
      success: (json) => {
        if (!json.count) {
          self.setState({
            isLoading: false,
            hasMore: false,
          });
          return;
        }

        this.setState((preState) => {
          const newData = [...preState.data, ...json.data_list];
          return ({
            dataSource: dataSource.cloneWithRows(newData),
            totalCount: json.total_count,
            isLoading: false,
            data: newData,
            offset: preState.offset + json.count,
          })
        });
      },
      error: (msg) => {
        const buttons = [
          {
            label: '知道了',
            onClick: () => {},
          },
        ];
        dialog.open('提示', msg, buttons, 'center');
      }
    });
    api.run();
  }
  handleDetail(id) {
    this.props.dispatch(routerAction.push(`/normal_work/detail/${id}`));
  }
  renderRow(rowData) {
    return (
      <div className="row-wrap" onClick={this.handleDetail.bind(this, rowData.id)}>
        {
          rowData.media ?
            <div className="content-img-wrap">
              <div><img src={`${RESOURCE_HOST}${rowData.media}`} alt="" className="img" /></div>
              <div className="content-wrap">{ rowData.title }</div>
            </div>
            :
            <div className="content-wrap">
              { rowData.title }
            </div>
        }
        <div className="time">
          发布时间：{rowData.modify_time ? moment(rowData.modify_time).format('YYYY年MM月DD日') : ''}
        </div>
      </div>
    )
  }
  render() {
    const { dataSource, pageSize, hasMore, data, totalCount } = this.state;
    const row = (rowData) => {
      if (data.length === totalCount && rowData.id === data[data.length - 1].id) {
        return (
          <div>
            {
              this.renderRow(rowData)
            }
            <div className="no-more">没有更多了</div>
          </div>
        )
      }
      return this.renderRow(rowData)
    };
    return (
      <div className="normal-work-page">
        <Title title="监管动态" />
        <div className="content-wrap">
          {
            !hasMore && data.length === 0 ? <div className="no-more">没有更多了</div> :
            <ListView
              dataSource={dataSource}
              renderFooter={() => (
                <div>
                  { this.state.isLoading && hasMore ? <div className="loading">加载中...</div> : '' }
                </div>
              )}
              renderRow={row}
              style={{
                overflow: 'auto',
                height: '100%',
                width: '100%',
                position: 'absolute'
              }}
              pageSize={pageSize}
              className="list"
              initialListSize={pageSize}
              scrollRenderAheadDistance={500}
              scrollEventThrottle={10}
              onScroll={() => {}}
              onEndReached={this.onEndReached}
              onEndReachedThreshold={10}
            />
          }
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}
export default connect(mapStateToProps)(NormalWork);

